//
// Created by none98 on 2021/9/24.
//

#include <spdlog/spdlog.h>
#include "DatabaseConnPool.h"


sql::Connection *DatabaseConnPool::GetConnection() {
    std::unique_lock<std::mutex> lock(connsMutex);
    while(connections.size()==0){
        connsVar.wait(lock);
    }
    sql::Connection* conn = connections.front();
    if(conn->isClosed()) conn->reconnect();
    connections.pop_front();
    return conn;
}

void DatabaseConnPool::CloseConnection(sql::Connection *conn) {
    std::unique_lock<std::mutex> lock(connsMutex);
    connections.push_back(conn);
    connsVar.notify_all();
}

void DatabaseConnPool::InitPool(const std::string &hostname, const std::string username, const std::string &password) {
    driver= sql::mysql::get_driver_instance();
    if(driver== nullptr){
        spdlog::error("get database driver going wrong!");
        return;
    }
    try{
        for(int i=0; i<10; i++){
            sql::Connection* conn = nullptr;
            conn = driver->connect(hostname,username,password);
            if(conn==nullptr){
                i--;
                spdlog::info("database connect failed");
            }else{
                connections.push_back(conn);
                std::unique_ptr<sql::Connection> p;
                p.reset(conn);
                realConnections.push_back(std::move(p));
            }
        }
    }catch(sql::SQLException &e){
        spdlog::error("database connect: {}",e.what());
    }
}
